import React from 'react';
import moment from 'moment';
import Calendar from '../Calendar';
import AdjustSchedule from '../AdjustSchedule';

export default ({ onChange }) => {
    const [rangeObj, setRangeObj] = React.useState();
    const [date, setDate] = React.useState(moment());
    const wrapRef = React.useRef();
    const calendarRef = React.useRef();
    const scheduleRef = React.useRef();
    const [scheduleHeight, setScheduleHeight] = React.useState(0);

    const adjustScheduleHeight = () => {
        setScheduleHeight(wrapRef.current.offsetHeight - calendarRef.current.offsetHeight);
    };

    const handleExpandChange = () => {
        setTimeout(() => {
            adjustScheduleHeight();
        });
    };

    const calendarProps = {
        value: date,
        onChange: setDate,
        onExpandChange: handleExpandChange
    };

    const handleTimeChange = arr => {
        if (!date) return;
        setRangeObj({ ...rangeObj, [date.format('YYYY-MM-DD')]: arr });
    };

    const getLength = () => {
        if (!rangeObj) return 0;
        let len = 0;
        Object.keys(rangeObj).forEach(key => {
            len += rangeObj?.[key]?.length || 0;
        });
        return len;
    };

    React.useEffect(() => {
        adjustScheduleHeight();
    }, []);

    React.useEffect(() => {
        if (onChange) {
            const arr = [];
            if (rangeObj) {
                Object.values(rangeObj).forEach(item => {
                    if (item && item.length > 0) {
                        item.forEach(({ range = [] }) => {
                            arr.push({
                                startTime: range?.[0] ? moment(range?.[0]).format('YYYY-MM-DD HH:mm:00') : '',
                                endTime: range?.[1] ? moment(range?.[1]).format('YYYY-MM-DD HH:mm:00') : ''
                            });
                        });
                    }
                });
            }
            onChange(arr);
        }
    }, [rangeObj]);

    return (
        <div ref={wrapRef} style={{ height: '100%', overflow: 'hidden' }}>
            <div
                ref={calendarRef}
                style={{ position: 'relative', paddingBottom: 12, borderBottom: '1px solid #F2F3F4' }}
            >
                <Calendar {...calendarProps} />
                <div style={{ position: 'absolute', right: 16, top: 12, fontSize: 14, color: '#2A2F3C' }}>
                    已选 {getLength()}
                </div>
            </div>
            <div ref={scheduleRef}>
                <AdjustSchedule
                    date={date}
                    height={scheduleHeight}
                    value={date ? rangeObj?.[date.format('YYYY-MM-DD')] : undefined}
                    onChange={handleTimeChange}
                />
            </div>
        </div>
    );
};
